package data.structures.sparsearray;

/**
 * 稀疏数组实现，稀疏数组第一行存放，二维数组的一共有几行几列，有多少个不同的值；其他存放不同值的行列
 * 二维数组转稀疏数组
 * 稀疏数组转二维数组
 */
public class sparseArray2 {

    public static void main(String[] args) {
        //创建二维数组
        int[][] chessArray1 = new int[11][11];
        chessArray1[1][2] = 1;
        chessArray1[2][3] = 2;
        chessArray1[1][1] = 4;
        System.out.println("===遍历初始二维数组===>");
        for (int[] ints : chessArray1) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }


        //二维数组转稀疏数组
        //1、获取二维数组的行列以及不同值的个数
        int sum = 0;//不同值的个数
        for (int i = 0; i < chessArray1.length; i++) {
            for (int j = 0; j < chessArray1[0].length; j++) {
                if (chessArray1[i][j] != 0) {
                    sum++;
                }
            }
        }
        int[][] sparseArr = new int[sum + 1][3];
        sparseArr[0][0] = chessArray1.length;
        sparseArr[0][1] = chessArray1[0].length;
        sparseArr[0][2] = sum;
        int count = 1;
        for (int i = 0; i < chessArray1.length; i++) {
            for (int j = 0; j < chessArray1[0].length; j++) {
                if (chessArray1[i][j] != 0) {
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArray1[i][j];
                    count++;
                }
            }
        }
        System.out.println("===稀疏数组遍历===>");
        for (int i = 0; i < sparseArr.length; i++) {
            for (int j = 0; j < sparseArr[0].length; j++) {
                System.out.printf("%d\t", sparseArr[i][j]);
            }
            System.out.println();
        }

        //稀疏数组转二维数组
        //先通过第一行设置二维数组行列
        int[][] chessArray2 = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
            for (int j = 0; j < sparseArr[0].length; j++) {
                chessArray2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
            }
        }
        System.out.println("===转换后的二维数组遍历===>");
        for (int i = 0; i < chessArray2.length; i++) {
            for (int j = 0; j < chessArray2[0].length; j++) {
                System.out.printf("%d\t", chessArray2[i][j]);
            }
            System.out.println();
        }
    }
}
